<?php
namespace System\Core\LogHandlers;

use System\Core\Log;

class DailyFileHandler extends BaseHandler {
    protected $filePath;
    protected $days;
    
    public function __construct($filePath, $days = 7, $level = Log::DEBUG) {
        parent::__construct($level);
        $this->filePath = $filePath;
        $this->days = $days;
    }
    
    public function handle($level, $message, array $context = []) {
        if (!$this->isHandling($level)) {
            return;
        }
        
        $date = date('Y-m-d');
        $file = $this->generateFilename($date);
        
        $log = $this->formatMessage($level, $message, $context);
        file_put_contents($file, $log, FILE_APPEND);
        
        $this->cleanOldLogs();
    }
    
    protected function generateFilename($date) {
        $dirname = dirname($this->filePath);
        $basename = basename($this->filePath, '.log');
        return "{$dirname}/{$basename}-{$date}.log";
    }
    
    protected function cleanOldLogs() {
        $dirname = dirname($this->filePath);
        $basename = basename($this->filePath, '.log');
        
        $files = glob("{$dirname}/{$basename}-*.log");
        
        if (count($files) > $this->days) {
            usort($files, function($a, $b) {
                return filemtime($a) < filemtime($b);
            });
            
            while (count($files) > $this->days) {
                $file = array_pop($files);
                @unlink($file);
            }
        }
    }
}